<template>
  <view class="cart-publish-wrap" >
    <view class="top_part">
      <view class="base_info">
        <view class="base_info_row" style="margin-bottom: 30rpx;" @tap="gotoPage('branch')">
          <view class="info_icon gray_icon">取</view>
          <view class="info_desc">
            <view class="thick">{{chooseBranch.name || ''}}</view>
            <view class="thin">{{chooseBranch.address || ''}}</view>
          </view>
          <view class="btn">&gt;</view>
        </view>
        <view class="base_info_row" @tap="gotoPage('address')">
          <view class="info_icon yellow_icon">收</view>
          <view class="info_desc">
            <view class="thick">{{`${addressInfo.delivery_name || ''}  ${addressInfo.mobile || ''}`}}</view>
            <view class="thin">{{ addressInfo.region || '' }}{{ addressInfo.address || '' }}</view>
          </view>
          <view class="btn">&gt;</view>
        </view>
      </view>
    </view>

    <view class="content_part">
      <view class="content_info">
        <view class="ceil" >
          <view class="label" >取件码</view>
          <view class="value" >
            <input v-model="cost_explain" maxlength="100" type="text" placeholder="请输入取件码" >
          </view>
        </view>
        <view class="ceil" >
          <view class="label" >取件姓名</view>
          <view class="value" >
            <input v-model="pick_up_name" maxlength="100" type="text" placeholder="请输入包裹收件人姓名" >
          </view>
        </view>
        <view class="ceil" >
          <view class="label" >取件尾号</view>
          <view class="value" >
            <input v-model="pick_up_phone" maxlength="100" type="text" placeholder="请输入包裹收件人手机尾号" >
          </view>
        </view>

        <view class="ceil" >
          <view class="label" >实付金额</view>
          <view v-if="fee" class="value" style="color: red;"  >
            ¥{{ fee }}
          </view>
        </view>
        <view class="ceil" >
          <view class="value" style="color: red;">多取件码用分号隔开，1公斤内1.5元，1公斤以上单独协商</view>
        </view>
      </view>
    </view>
    <view class="agree" @tap="agree = !agree" >
        <view :class="['iconfont icon-circle', agree ? 'icon-xuanzhong on' : 'icon-xuanzhongyuandian']" ></view>
        <view style="color: #999999;" >同意<text style="color: #007AFF;" @tap.stop="handleToXieyi" >《用户协议》</text></view>
      </view>
    <!-- 进行中 -->
     <view class="btn-box">
       <button
         class="pp-button cancel-btn"
         hover-class="pp-button--active"
         @tap="handlePublish"
       >
         确认发布
       </button>
     </view>

    <!-- 时间选择器 -->
    <timePicker
    :show.sync="timeShow"
    @listenConfirmTime="listenConfirmTime"
    @listenStandardDate="listenStandardDate"
    ></timePicker>

  </view>
</template>

<script>
  import {
    STORE_PAO_TUI_ORDER,
    ERRAND_FEE,
    QUERY_BRANCH,
    RECEIVER_LIST,
    USER_INFO,
  } from '@/api';
  import { checkRunPhone } from '@/tool';
  import get from 'lodash/get';
  import Stepper from '@/basic-components/u-stepper/index.vue';

  export default {
    components: {
    Stepper,
  },
    data() {
      return {
        timeShow: false,
        start_point: '',  //出发地
        destination: '',  //目的地
        contact: '',
        contact_phone: '',
        agree: false,
        cost_explain: '',
        pick_up_name: '',
        pick_up_phone: '',
        fee: undefined,
        chooseBranch: {},
        addressInfo: {},
      }
    },
    onLoad() {
      // 跑腿费用
      this.getRunFee();
      this.queryBranch();
      this.fetchAddessList();
    },

    onShow(option) {
      console.log('onShow', option);
      // 地址选择
      if(option){
        if (option.type === 'address') {
          this.addressInfo = option.params;
        }
        if (option.type === 'branchInfo') {
          this.chooseBranch = option.params;
        }
      }

    },

    methods: {

      handleToXieyi() { //
      this.$navigate({
        page: 'xieyi',
      });
    },

      /**
       * 跑腿费用
       */
      getRunFee() {
        let params = {};
            params['key'] = 'errand_fee';
        this.$http.get(ERRAND_FEE, params)
          .then(res => {
            this.fee = res.data.fee;
          });
      },

      async queryBranch() {
        const params = {
          regionId: uni.getStorageSync('regionId'),
        };
        const brachInfoListRes = await this.$http.get(QUERY_BRANCH, params);
        this.chooseBranch = get(brachInfoListRes, 'data[0]', {});
      },

      async fetchAddessList() {
        const userInfoRes = await this.$http.get(USER_INFO);
        const regions_code = get(userInfoRes, 'data.region.regions_code', '');
        if(regions_code) {
          const addressLsitRes =  await this.$http.get(
            RECEIVER_LIST, {
            'per_page': 100
          });
          const addressList = (addressLsitRes.data || []).filter((item)=>{
            return item.village === regions_code;
          });
          this.addressInfo = addressList[0] || {};
        } else {
          this.addressInfo = {};
        }
      },
      gotoPage(type) {
        if(type === 'address') {
          this.$navigate({
            page: 'addressSelection',
          });
        }
        if(type === 'branch') {
          this.$navigate({
            page: 'branchSelection',
          });
        }
      },

      /**
       * 创建订单
       */
      handlePublish() {
        if(!this.agree){
        uni.showToast({
          title: '请同意用户协议',
          icon: 'none',
        });
        return
      }
        if(Object.keys(this.chooseBranch).length <= 0) {
          uni.showToast({
            title: '该区域无网点无法下单',
            icon: 'none',
          });
          return
        }
        if(Object.keys(this.addressInfo).length <= 0) {
          uni.showToast({
            title: '请选择收件信息',
            icon: 'none',
          });
          return
        }
        if(!this.cost_explain.trim()||!this.pick_up_name.trim()||!this.pick_up_phone.trim()) {
          uni.showToast({
            title: '请输入完整取件信息',
            icon: 'none',
          });
          return
        }
     
        uni.showToast({
          title: '请求中...',
          mask: true,
          icon: 'loading',
          duration: 300000,
        });

        const params = {
          region_id: uni.getStorageSync('regionId'),
          branch_id: this.chooseBranch.id,
          delivery_id: this.addressInfo.id,
          pick_up_code: this.cost_explain,
          pick_up_name:this.pick_up_name,
          pick_up_phone:this.pick_up_phone,
          agree:this.agree, 
        };

        this.$http.post(STORE_PAO_TUI_ORDER, params).then((res) => {
          
          // 去支付
          this.payOrder(res.data)
        }).catch(() => {
          console.log('----------this-1111-----'+JSON.stringfy(res))
          uni.hideToast();
        })
      },
      /**
       * 去支付
       */
      payOrder(data) {
        uni.requestPayment({
          timeStamp: data.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
          nonceStr: data.nonceStr, // 支付签名随机串，不长于 32 位
          package: data.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
          signType: data.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
          paySign: data.paySign,
          success: res => {
            console.log('----------this-3333-----')
            uni.hideToast();
            if (res.errMsg === 'requestPayment:ok') {

              setTimeout(() => {
                uni.showToast({
                  title: '创建成功',
                  icon: 'success',
                });
              }, 300)

              setTimeout(() => {
                this.$navigate({
                  type: 2,
                  page: 'runOrder'
                });
              }, 1000)
            }
          },
          fail: (error) => {
            uni.hideToast();
            console.log('----------this-222-----'+JSON.stringify(error))
          },
        });
      }
    }

  }
</script>

<style lang="less" >
  .cart-publish-wrap{
    min-height: 100vh;
    padding-bottom: 150rpx;
    padding-bottom: calc(150rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(150rpx + env(safe-area-inset-bottom));
    background-color: #f5f5f5;
    .top_part {
      background-image: linear-gradient(#FFF27C, #F9F9F5);
      padding: 0 30rpx;
      .base_info {
        background-color: #fff;
        padding: 36rpx 24rpx;
        border-radius: 12rpx;
        .base_info_row {
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: space-between;
          .info_icon{
            width: 60rpx;
            height: 60rpx;
            border-radius: 30rpx;
            color: #fff;
            display: flex;
            flex-direction: row;
            justify-content: center;
            align-items: center;
          }
          .gray_icon {
            background-color: #999999;
          }
          .yellow_icon {
            background-color: #fedd00;
          }
          .info_desc {
            flex: 1;
            margin-left: 16rpx;
            line-height: 1.25;
            .thick {
              font-size: 28rpx;
              font-weight: bold;
              margin-bottom: 8rpx;
            }
            .thin {
              color: #888;
            }
          }
          .btn {
            display: flex;
            flex-direction: row;
            justify-content: center;
            align-items: center;
            width: 50rpx;
            font-size: 40rpx;
            color: #fedd00;
            font-weight: bold;
          }
        }
      }
    }
    
    .content_part {
      margin-top: 20rpx;
      padding: 0 30rpx;
      .content_info{
        background-color: #fff;
        border-radius: 12rpx;
      }
    }

    .ceil{
      display: flex;
      align-items: center;
      padding: 24rpx;
      border-bottom: 1px solid #EEEEEE;
      .label{
        width: 180rpx;
        flex-shrink: 0;
      }
      .value{
        flex: 1;
      }
      .arrow{
        font-size: 32rpx;
        flex-shrink: 0;
        color: #999999;
      }
    }
    .img-box{
      position: relative;
      width: 200rpx;
      height: 200rpx;
      .img-file{
        width: 100%;
        height: 100%;
      }
      .del{
        position: absolute;
        right: 0;
        top: 0;
        margin-right: -20rpx;
        margin-top: -20rpx;
        font-size: 36rpx;
        color: #ff0000;
      }
    }
    .agree{
    display: flex;
    align-items: center;
    margin-top: 20rpx;
    margin-bottom: 20rpx;
    justify-content: center;
    .icon-circle{
      margin-right: 10rpx;
      font-size: 28rpx;
      color: #999999;
    }
    .on{
      color: #4caf50;
    }
  }
    .upload-box{
      width: 710rpx;
      padding-bottom: 24rpx;
      border-radius: 20rpx;
      margin: auto;
      margin-bottom: 24rpx;
      background-color: #ffffff !important;
      background-size: 100% !important;

      .title{
        display: flex;
        align-items: center;
        padding: 24rpx;
        .title-main{
          font-size: 28rpx;
          font-weight: 500;
        }
        .title-desc{
          font-size: 24rpx;
          margin-left: 16rpx;
          color: #999999;
        }
      }
      .box-solid{
        width: 200rpx;
        height: 200rpx;
        margin-left: 24rpx;
        border-radius: 12rpx;
        border: 1px solid #EEEEEE;
      }
    }
    .btn-box {
      position: fixed;
      bottom: 0;
      left: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 136rpx;
      .cancel-btn {
        width: 710rpx;
        height: 92rpx;
        font-size: 32rpx;
        background-color: #fedd00;
      }
    }
  }
</style>
